<template>
  <div class="wrap">
    <a-card size="small" hoverable>
      <a-page-header
        style="padding: 0; margin: 0 16 16 16"
        title="返回"
        sub-title="MX0124030001"
        @back="() => $router.go(-1)"
      />
    </a-card>
    <a-card size="small" style="margin-top: 8px" hoverable>
      <template #extra
        ><a-button type="link" @click="hideBaseInfo">{{ hideText }}</a-button></template
      >
      <template #title><BaseTitle title="基础信息" /></template>
      <transition name="base">
        <div style="display: flex; margin-top: 8px" transiton="base" v-show="showBaseFlag">
          <!-- <div style="width: 240px; margin-right: 32px">
        <img
          style="width: 240px; height: 180px; object-fit: cover"
          alt="example"
          src="https://os.alipayobjects.com/rmsportal/QBnOOoLaAfKPirc.png"
      /></div> -->
          <div style="flex: 1">
            <a-descriptions :column="4">
              <a-descriptions-item label="设备名称" :labelStyle="{ fontWeight: 'bold' }"
                >搅拌桩1号</a-descriptions-item
              >
              <a-descriptions-item label="设备编号" :labelStyle="{ fontWeight: 'bold' }"
                >MX0124030001</a-descriptions-item
              >
              <a-descriptions-item label="设备型号" :labelStyle="{ fontWeight: 'bold' }">
                XX-xxxxxx
              </a-descriptions-item>
              <a-descriptions-item label="设备版本号" :labelStyle="{ fontWeight: 'bold' }">
                1.1.1
              </a-descriptions-item>

              <a-descriptions-item label="机器编号" :labelStyle="{ fontWeight: 'bold' }"
                >123</a-descriptions-item
              >
              <a-descriptions-item label="机器型号" :labelStyle="{ fontWeight: 'bold' }"
                >123</a-descriptions-item
              >
              <a-descriptions-item label="当前运行状态" :labelStyle="{ fontWeight: 'bold' }"
                ><a-tag color="cyan">运行中</a-tag></a-descriptions-item
              >
              <a-descriptions-item label="当前工作状态" :labelStyle="{ fontWeight: 'bold' }"
                ><a-tag color="blue">喷浆</a-tag></a-descriptions-item
              >
              <a-descriptions-item label="最近上线时间" :labelStyle="{ fontWeight: 'bold' }"
                >2024-03-21 16:39:33</a-descriptions-item
              >
            </a-descriptions>
          </div>
          <!-- <div style="width: 520px; height: 180px; display: flex">
        <div style="width: 120px; height: 100%; display: flex">
          <Echarts :option="option2" style="display: inline-block; width: 120px" />
        </div>
        <div style="flex: 1; display: flex">
          <Echarts :option="option" style="display: inline-flex; width: 50%" />
          <Echarts :option="option" style="display: inline-flex; width: 50%" />
        </div>
      </div> -->
        </div>
      </transition>
    </a-card>
    <a-card size="small" style="margin-top: 8px" hoverable>
      <!-- <template #title><BaseTitle title="实时指标" /></template> -->
      <!-- <div style="width: 100%; height: 240px; display: inline-block">
      <Echarts :option="option2" style="display: inline-block; width: 260px" />
      <Echarts :option="option" style="display: inline-block; width: 340px" />
      <Echarts :option="option" style="display: inline-block; width: 340px" />
      <Echarts :option="option" style="display: inline-block; width: 340px" />
      <Echarts :option="option" style="display: inline-block; width: 340px" />
    </div> -->
      <a-tabs v-model:activeKey="activeKey" @change="changeTab">
        <template #rightExtra>
          <div style="float: right">
            <!--            <a-checkbox-group v-model:value="state.value3" :options="piples" />-->
            <a-range-picker v-model:value="timePicker" style="margin-right: 8px" />
            <a-button type="primary" style="margin-right: 8px" @click="list">查询</a-button>
            <a-button type="primary" @click="list">导出</a-button>
          </div>
        </template>
        <a-tab-pane key="1" tab="历史数据">
          <a-table
            :loading="loading"
            :dataSource="data"
            :columns="columns"
            :pagination="pagination"
            size="middle"
            @change="handleTableChange"
            :scroll="{ x: 'max-content' }"
            rowClassName="hideIcon"
            :showExpandColumn="false"
            :expandRowByClick="true"
            :expandedRowKeys="expandedRowKeys"
            :customRow="customRow"
            rowKey="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'dataSource'">
                <a-tag v-if="record.dataSource === 1" color="cyan">开始</a-tag>
                <a-tag v-else-if="record.dataSource === 2" color="cyan">结束</a-tag>
                <a-tag v-else-if="record.dataSource === 3" color="cyan">暂停</a-tag>
                <a-tag v-else-if="record.dataSource === 4" color="cyan">段数据</a-tag>
                <a-tag v-else-if="record.dataSource === 5" color="cyan">定时</a-tag>
                <a-tag v-else color="red">未知</a-tag>
              </template>
              <template v-if="column.key === 'pileStatus'">
                <a-tag v-if="record.pileStatus === 1" color="cyan">停钻</a-tag>
                <a-tag v-else-if="record.pileStatus === 2" color="cyan">下钻</a-tag>
                <a-tag v-else-if="record.pileStatus === 3" color="cyan">提钻</a-tag>
                <a-tag v-else-if="record.pileStatus === 4" color="cyan">复下</a-tag>
                <a-tag v-else-if="record.pileStatus === 5" color="cyan">复提</a-tag>
                <a-tag v-else color="red">未知</a-tag>
              </template>
              <template v-if="column.key === 'slurSta'">
                <a-tag v-if="record.pileStatus === 0" color="cyan">不喷浆</a-tag>
                <a-tag v-else-if="record.pileStatus === 1" color="cyan">喷浆</a-tag>
                <a-tag v-else color="red">未知</a-tag>
              </template>
              <template v-if="column.key === 'operation'"> </template>
            </template>
            <template #expandedRowRender="{ record }">
              <p style="margin: 0">
                {{ record.pileNo }}
              </p>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="2" tab="动态统计">
          <Echarts
            :option="option3"
            width="100%"
            height="300px"
            style="display: inline-flex; width: 100%; height: 300px"
          />
        </a-tab-pane>
        <a-tab-pane key="3" tab="预警记录">
          <a-table
            :loading="loading"
            :dataSource="warnData"
            :columns="warnColumns"
            :pagination="pagination"
            size="middle"
            @change="handleTableChange"
            :scroll="{ x: 'max-content' }"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'dataSource'">
                <a-tag v-if="record.dataSource === 1" color="cyan">开始</a-tag>
                <a-tag v-else-if="record.dataSource === 2" color="cyan">结束</a-tag>
                <a-tag v-else-if="record.dataSource === 3" color="cyan">暂停</a-tag>
                <a-tag v-else-if="record.dataSource === 4" color="cyan">段数据</a-tag>
                <a-tag v-else-if="record.dataSource === 5" color="cyan">定时</a-tag>
                <a-tag v-else color="red">未知</a-tag>
              </template>
              <template v-if="column.key === 'pileStatus'">
                <a-tag v-if="record.pileStatus === 1" color="cyan">停钻</a-tag>
                <a-tag v-else-if="record.pileStatus === 2" color="cyan">下钻</a-tag>
                <a-tag v-else-if="record.pileStatus === 3" color="cyan">提钻</a-tag>
                <a-tag v-else-if="record.pileStatus === 4" color="cyan">复下</a-tag>
                <a-tag v-else-if="record.pileStatus === 5" color="cyan">复提</a-tag>
                <a-tag v-else color="red">未知</a-tag>
              </template>
              <template v-if="column.key === 'status'">
                <a-tag v-if="record.pileStatus === 0" color="cyan">已处理</a-tag>
                <a-tag v-else-if="record.pileStatus === 1" color="cyan">未处理</a-tag>
                <a-tag v-else color="red">未知</a-tag>
              </template>
              <template v-if="column.key === 'operation'"> </template>
            </template>
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import { h, ref, onMounted, reactive, watch, computed } from 'vue'
  import {
    DeleteOutlined,
    SettingOutlined,
    EditOutlined,
    EllipsisOutlined,
  } from '@ant-design/icons-vue'
  import { FormInstance, message } from 'ant-design-vue'
  import type { TreeProps } from 'ant-design-vue'
  import { BaseTitle } from '/@/components/Title'
  import { listRole, addRole, deleteRole, listPermission, setPermission } from '/@/api/sys/role'
  import { listDeviceRecord } from '/@/api/pd/deviceRecord'
  import { DeviceRecordResult, DeviceRecordSo } from '/@/api/pd/model/deviceRecordModel'
  import { listWarning } from '/@/api/pd/warning'
  import { WarningListResult, WarningListSo } from '/@/api/pd/model/warningModel'
  import { pileSimple } from '/@/api/pd/model/pileModel'
  import { Modal } from 'ant-design-vue'
  import Echarts from '/@/components/ReEcharts/index.vue'
  import { EChartsOption } from 'echarts'
  import type { Dayjs } from 'dayjs'
  import { useRoute } from 'vue-router'

  const route = useRoute()

  const open = ref<boolean>(false)
  const openPermission = ref<boolean>(false)
  const loading = ref(false)
  const showBaseFlag = ref(true)
  const hideText = ref('收起')
  const expandedRowKeys = ref<string[]>([])
  type RangeValue = [Dayjs, Dayjs]
  const timePicker = ref<RangeValue>()
  const activeKey = ref<string>('1')
  let data = ref<DeviceRecordResult[]>([])
  let charDataX = ref<string[]>([])
  let charDataY = ref<string[]>([])
  let x = ref<string[]>([])
  let y = ref<number[]>([])
  const piples = ref<pileSimple[]>([])

  const option = reactive<EChartsOption>({
    title: {
      //标题
      show: true,
      text: 'CPU利用率',
      left: 'center',
      top: '82%',
      textStyle: {
        //标题样式
        color: '#333',
        fontSize: 14,
        fontWeight: 600,
      },
    },
    series: [
      {
        max: 250, //最大刻度值
        type: 'gauge',
        progress: {
          show: true,
          width: 10,
        },
        axisLine: {
          lineStyle: {
            width: 10,
          },
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          length: 8,
          lineStyle: {
            width: 2,
            color: '#999',
          },
        },
        axisLabel: {
          distance: 10,
          color: '#999',
          fontSize: 14,
        },
        anchor: {
          show: true,
          showAbove: true,
          size: 12,
          itemStyle: {
            borderWidth: 6,
          },
        },
        title: {
          show: false,
          offsetCenter: [0, '90%'],
        },
        detail: {
          valueAnimation: true,
          fontSize: 32,
          offsetCenter: [0, '70%'],
        },
        data: [
          {
            value: 306,
            name: 'CPU利用率',
          },
        ],
      },
    ],
  })

  const option2 = reactive<EChartsOption>({
    title: {
      text: '深度(m)',
      bottom: '10%',
      left: 'center',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
      // formatter: function (params) {
      //   var tar = params[1]
      //   return tar.name + '<br/>' + tar.seriesName + ' : ' + tar.value
      // },
    },
    grid: {
      top: '10%',
      left: '0%',
      right: '30%',
      bottom: 40,
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      show: false,
      splitLine: { show: false },

      data: ['深度(m)'],
    },
    yAxis: {
      type: 'value',
      show: false,
    },
    series: [
      {
        barWidth: 20,
        name: '剩余深度',
        type: 'bar',
        stack: '深度(m)',
        itemStyle: {
          borderColor: 'transparent',
          color: '#eee',
        },
        emphasis: {
          itemStyle: {
            borderColor: 'transparent',
            color: 'red',
          },
        },
        data: [2],
      },
      {
        name: '当前深度',
        type: 'bar',
        stack: '深度(m)',
        label: {
          show: true,
          position: 'inside',
          formatter: (params) => params.value + '%',
        },
        data: [98],
      },
    ],
  })

  const option3 = ref<EChartsOption>()
  option3.value = {
    tooltip: {
      trigger: 'axis',
      position: function (pt) {
        return [pt[0], '10%']
      },
    },
    title: {
      left: 'center',
      text: 'Large Area Chart',
    },
    toolbox: {
      feature: {
        dataZoom: {
          yAxisIndex: 'none',
        },
        restore: {},
        saveAsImage: {},
      },
    },
    xAxis: {
      type: 'time',
      // data: (() => {
      //   let list: string[] = []
      //   data.value.map((item) => {
      //     list.push(item.dataTime)
      //   })
      //   return list
      // })(),
    },
    yAxis: {
      type: 'value',
      boundaryGap: [0, '100%'],
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 10,
      },
      {
        start: 0,
        end: 10,
      },
    ],
    series: [
      {
        name: 'Fake Data',
        type: 'line',
        symbol: 'none',
        sampling: 'lttb',
        itemStyle: {
          color: 'rgb(255, 70, 131)',
        },
        data: undefined,
      },
    ],
  }

  const pagination = ref({
    total: 0,
    current: 1,
    pageSize: 10,
    size: '',
    showSizeChanger: false,
    showQuickJumper: false,
  })

  let recordSo = reactive<DeviceRecordSo>({
    deviceCode: undefined,
    machCode: undefined,
    startTime: undefined,
    endTime: undefined,
    tenantId: undefined,
    projectId: undefined,
    pileId: undefined,
  })

  let warnSo = reactive<WarningListSo>({
    deviceCode: undefined,
    machCode: undefined,
    startTime: undefined,
    endTime: undefined,
    tenantId: undefined,
    projectId: undefined,
    pileId: undefined,
  })

  const pageParam = computed(() => ({
    query: recordSo,
    current: pagination.value?.current,
    size: pagination.value?.pageSize,
  }))

  const warnPageParam = computed(() => ({
    query: warnSo,
    current: pagination.value?.current,
    size: pagination.value?.pageSize,
  }))

  const columns = [
    {
      title: '桩编码',
      dataIndex: 'pileNo',
      key: 'pileNo',
      align: 'center',
      width: 140,
      fixed: 'left',
    },
    {
      title: '数据来源',
      dataIndex: 'dataSource',
      key: 'dataSource',
      align: 'center',
      width: 80,
    },
    {
      title: '桩状态',
      dataIndex: 'pileStatus',
      key: 'pileStatus',
      align: 'center',
      width: 80,
    },
    {
      title: '喷浆状态',
      dataIndex: 'slurSta',
      key: 'slurSta',
      align: 'center',
      width: 80,
    },
    {
      title: '倾角x',
      dataIndex: 'angleX',
      key: 'angleX',
      align: 'center',
      width: 80,
    },
    {
      title: '倾角y',
      dataIndex: 'angleY',
      key: 'angleY',
      align: 'center',
      width: 80,
    },
    {
      title: '垂直度',
      dataIndex: 'vert',
      key: 'vert',
      align: 'center',
      width: 80,
    },
    {
      title: '实时钻杆电流(A)',
      dataIndex: 'cur',
      key: 'cur',
      align: 'center',
      width: 120,
    },
    {
      title: '实时压力(Mpa)',
      dataIndex: 'pressure',
      key: 'pressure',
      align: 'center',
      width: 80,
    },
    {
      title: '实时流量(L/Min)',
      dataIndex: 'flow',
      key: 'flow',
      align: 'center',
      width: 140,
    },
    {
      title: '实时密度(g/cm³)',
      dataIndex: 'density',
      key: 'density',
      align: 'center',
      width: 140,
    },
    {
      title: '实时速度(cm/min)',
      dataIndex: 'speed',
      key: 'speed',
      align: 'center',
      width: 140,
    },
    {
      title: '实时段灰量(kg)',
      dataIndex: 'segAsh',
      key: 'segAsh',
      align: 'center',
      width: 140,
    },
    {
      title: '实际桩长(m)',
      dataIndex: 'pileDepth',
      key: 'pileDepth',
      align: 'center',
      width: 140,
    },
    {
      title: '初搅深度(m)',
      dataIndex: 'firDepth',
      key: 'firDepth',
      align: 'center',
      width: 140,
    },
    {
      title: '复搅深度(m)',
      dataIndex: 'secDepth',
      key: 'secDepth',
      align: 'center',
      width: 140,
    },
    {
      title: '空搅深度(m)',
      dataIndex: 'emDepth',
      key: 'emDepth',
      align: 'center',
      width: 140,
    },
    {
      title: '当前深度(m)',
      dataIndex: 'curDepth',
      key: 'curDepth',
      align: 'center',
      width: 140,
    },
    {
      title: '累计空搅浆量(L)',
      dataIndex: 'emSlur',
      key: 'emSlur',
      align: 'center',
      width: 140,
    },
    {
      title: '累计空搅灰量(kg)',
      dataIndex: 'emAsh',
      key: 'emAsh',
      align: 'center',
      width: 140,
    },
  ]
  const warnColumns = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      align: 'center',
      width: 140,
      fixed: 'left',
    },
    {
      title: '设备编码',
      dataIndex: 'deviceCode',
      key: 'deviceCode',
      align: 'center',
      width: 140,
      fixed: 'left',
    },
    {
      title: '机器编码',
      dataIndex: 'machCode',
      key: 'machCode',
      align: 'center',
      width: 80,
    },
    {
      title: '数据来源',
      dataIndex: 'dataSource',
      key: 'dataSource',
      align: 'center',
      width: 80,
    },
    {
      title: '桩状态',
      dataIndex: 'pileStatus',
      key: 'pileStatus',
      align: 'center',
      width: 80,
    },
    {
      title: '预警级别',
      dataIndex: 'warningLevel',
      key: 'warningLevel',
      align: 'center',
      width: 80,
    },
    {
      title: '预警项',
      dataIndex: 'warningItem',
      key: 'warningItem',
      align: 'center',
      width: 80,
    },
    {
      title: '预警值',
      dataIndex: 'warningValue',
      key: 'warningValue',
      align: 'center',
      width: 80,
    },
    {
      title: '阈值范围',
      dataIndex: 'warningLimit',
      key: 'warningLimit',
      align: 'center',
      width: 80,
    },
    {
      title: '预警时间',
      dataIndex: 'warningTime',
      key: 'warningTime',
      align: 'center',
      width: 120,
    },
    {
      title: '预警状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: 80,
    },
  ]

  let warnData = ref<WarningListResult[]>([])
  let checkedKeys = ref<string[]>(['3'])

  // interface Props {
  //   width?: string
  //   height?: string
  //   option: EChartsOption
  // }
  // const props = withDefaults(defineProps<Props>(), {
  //   width: '100%',
  //   height: '100%',
  //   option: () => ({}),
  // })

  watch(checkedKeys, () => {
    console.log('checkedKeys', checkedKeys)
  })

  watch(timePicker, () => {
    recordSo.startTime = timePicker.value?.[0]?.format('YYYY-MM-DD 00:00:00')
    recordSo.endTime = timePicker.value?.[1]?.format('YYYY-MM-DD 23:59:59')
    warnSo.startTime = timePicker.value?.[0]?.format('YYYY-MM-DD 00:00:00')
    warnSo.endTime = timePicker.value?.[1]?.format('YYYY-MM-DD 23:59:59')
    updateData(false)
  })

  //#endregion

  onMounted(() => {
    recordSo.deviceCode = route.query?.deviceCode?.toString() || undefined
    recordSo.machCode = route.query?.machCode?.toString() || undefined
    list()
  })

  async function list() {
    loading.value = true
    const res = await listDeviceRecord(pageParam.value)
    console.log('res', res)
    data.value = res.records
    pagination.value.total = Number(res.total)
    pagination.value.current = Number(res.current)
    loading.value = false
  }

  function handleTableChange(page) {
    pagination.value.current = page.current
    updateData(false)
  }

  const updateData = (init) => {
    if (init) {
      pagination.value.total = 0
      pagination.value.current = 1
    }
    switch (activeKey.value) {
      case '1':
        list()
        break
      case '2':
        console.log('option3', option3)
        option3.value!.series![0].data = data.value.map((item) => [item.dataTime, item.curDepth])
        // list()
        break
      case '3':
        listWarn()
        break
    }
  }

  //#region 用户

  const hideBaseInfo = () => {
    showBaseFlag.value = !showBaseFlag.value
    hideText.value = showBaseFlag.value ? '收起' : '展开'
  }

  const customRow = (record) => {
    return {
      onClick: () => {
        if (record.id == expandedRowKeys.value[0]) {
          expandedRowKeys.value = []
        } else {
          expandedRowKeys.value = [record.id]
        }
      },
    }
  }

  async function listWarn() {
    loading.value = true
    const res = await listWarning(warnPageParam.value)
    warnData.value = res.records
    pagination.value.total = Number(res.total)
    pagination.value.current = Number(res.current)
    loading.value = false
  }

  const changeTab = () => {
    timePicker.value = undefined
    updateData(true)
  }

  const drawChart = () => {}
  //#endregion
</script>

<style lang="scss" scoped>
  .wrap {
    margin: 0px;
    padding: 0px 16px 16px 16px;
    background-color: #f0f2f5;
    max-width: calc(100vw - 230px);
    &-table {
      margin-top: 16px;
    }
  }

  .base-enter-active,
  .base-leave-active {
    transition: opacity 0.4s;
  }
  .base-enter,
  .base-leave-active {
    opacity: 0;
  }
</style>
